package com.qianda.qdminiapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.exception.ExceptionCode;
import com.qianda.qdminiapp.common.exception.SimpleException;
import com.qianda.qdminiapp.common.future.CommandFuture;
import com.qianda.qdminiapp.common.future.SendData;
import com.qianda.qdminiapp.common.rabbitmq.MsgProducer;
import com.qianda.qdminiapp.config.CompanyProperties;
import com.qianda.qdminiapp.dao.device.QqdStoreDao;
import com.qianda.qdminiapp.dao.user.QqdUserBuyLimitDao;
import com.qianda.qdminiapp.dao.user.QqdUserDao;
import com.qianda.qdminiapp.domain.model.device.QqdDevice;
import com.qianda.qdminiapp.dao.device.QqdDeviceDao;
import com.qianda.qdminiapp.domain.model.device.QqdStore;
import com.qianda.qdminiapp.domain.model.user.QqdUser;
import com.qianda.qdminiapp.domain.model.user.QqdUserBuyLimit;
import com.qianda.qdminiapp.service.QqdDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianda.qdminiapp.service.order.AbstractOrderAndPay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author cw
 * @since 2019-08-14
 */
@Service
@EnableConfigurationProperties({ CompanyProperties.class })
public class QqdDeviceServiceImpl extends ServiceImpl<QqdDeviceDao, QqdDevice> implements QqdDeviceService {

    private static Logger LOGGER = LoggerFactory.getLogger(QqdDeviceServiceImpl.class);

    @Autowired
    private QqdDeviceDao qqdDeviceDao;

    @Autowired
    private QqdUserDao qqdUserDao;

    @Autowired
    private QqdStoreDao qqdStoreDao;

    @Autowired
    private CompanyProperties companyProperties;

    @Autowired
    private MsgProducer msgProducer;

    @Autowired
    private QqdUserBuyLimitDao qqdUserBuyLimitDao;

    @Override
    public QqdDevice findByImei(String imei) {
        QueryWrapper<QqdDevice> qqdDeviceQueryWrapper = new QueryWrapper<>();
        qqdDeviceQueryWrapper.eq("imei",imei).eq("status", CommonConstant.Status.STATUS_NORMAL);
        qqdDeviceQueryWrapper.eq("company_id",companyProperties.getId());
        QqdDevice qqdDevice = qqdDeviceDao.selectOne(qqdDeviceQueryWrapper);
        return qqdDevice;
    }

    @Override
    @Transactional
    public void updateOnline(Long id,Integer onlineStatus) {
        qqdDeviceDao.setDeviceOnLine(id,onlineStatus);
    }

    @Override
    public Integer checkIsNewActivity(Long userId, Long id) {
        QqdUser qqdUser = qqdUserDao.selectById(userId);
        if(qqdUser.getIsNewUser() == null || qqdUser.getIsNewUser() == CommonConstant.IsNewUser.IS_NOT_NEW_USER){
            return 1;
        }
        QqdDevice qqdDevice = qqdDeviceDao.selectById(id);
        
        if(qqdDevice.getDeviceNewActivity() ==null || qqdDevice.getDeviceNewActivity() == CommonConstant.DeviceIsNewActivity.DEVICE_IS_NEW_ACTIVITY_NO){
            return 2;
        }
        QqdStore qqdStore = qqdStoreDao.selectById(qqdDevice.getStoreId());
        if(qqdStore.getIsNewActivity() == null || qqdStore.getIsNewActivity() == CommonConstant.DeviceIsNewActivity.DEVICE_IS_NEW_ACTIVITY_NO){
            return 3;
        }
        return 0;
    }

    @Override
    public Integer findSign(String imei) {

        SendData sendData = new SendData(null,1);
        sendData.put("command",4);
        sendData.put("imei",imei);
        sendData.put("protocolsV",CommonConstant.DeviceProtocolsVersion.DEVICE_PROTOCOLS_VERSION_OLD);
        String futureId = imei;
        CommandFuture send = msgProducer.send(sendData, futureId, 10l);
        try{
            Map<String,Object> result = (Map<String, Object>) send.get(10l, TimeUnit.SECONDS);
            if(result != null){
                Integer sign = Integer.valueOf(result.get("sign").toString().trim());
                LOGGER.info("信号值为:"+sign);
                if(sign != null){
                    return sign;
                }

            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public QqdDevice findById(Long id, Long userId) {
        Long companyId = companyProperties.getId();
        QueryWrapper<QqdDevice> qqdDeviceQueryWrapper = new QueryWrapper<>();
        qqdDeviceQueryWrapper.eq("id",id);
        qqdDeviceQueryWrapper.eq("company_id",companyId);
        QqdDevice device = qqdDeviceDao.selectOne(qqdDeviceQueryWrapper);
        if(device == null){
            throw new SimpleException(ExceptionCode.EX_DEVICE_ERROR);
        }
        //  QqdDevice device = qqdDeviceDao.selectById(id);
        QqdStore qqdStore = qqdStoreDao.selectById(device.getStoreId());
        if(qqdStore.getIsPriceLimit()!=null &&   qqdStore.getIsPriceLimit() == CommonConstant.IsPriceLimit.IS_PRICE_LIMIT_YES){
            if(device.getDevicePrice().compareTo(qqdStore.getLimitPrice()) <0){
                QueryWrapper<QqdUserBuyLimit> qqdUserBuyLimitQueryWrapper = new QueryWrapper<>();
                qqdUserBuyLimitQueryWrapper.eq("user_id",userId);
                qqdUserBuyLimitQueryWrapper.eq("buy_date", LocalDate.now());
                QqdUserBuyLimit qqdUserBuyLimit = qqdUserBuyLimitDao.selectOne(qqdUserBuyLimitQueryWrapper);
                if(qqdUserBuyLimit != null && qqdUserBuyLimit.getBuyTime()>= qqdStore.getLimitTime()){
                    device.setDevicePrice(qqdStore.getOriginalPrice());
                }
            }
        }
        return device;
    }
}
